package com.xjlsoft.weather.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xjlsoft.weather.dto.ExportDto;
import com.xjlsoft.weather.dto.ExportResponseDto;
import com.xjlsoft.weather.dto.PageDto;
import com.xjlsoft.weather.dto.RadiationMinListDto;
import com.xjlsoft.weather.dto.ResultEntity;
import com.xjlsoft.weather.dto.WeatherDataQueryDto;
import com.xjlsoft.weather.entity.GroundDataExcelDto;
import com.xjlsoft.weather.entity.RadiationMin;
import com.xjlsoft.weather.entity.RadiationMinExcelDto;
import com.xjlsoft.weather.enums.ResultCodeEnum;
import com.xjlsoft.weather.mapper.RadiationMinMapper;
import com.xjlsoft.weather.service.RadiationMinExcelDtoService;
import com.xjlsoft.weather.service.RadiationMinService;
import com.xjlsoft.weather.util.ResultUtil;
import com.xjlsoft.weather.util.WeatherDataUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 辐射资料-中国气象辐射啄分钟资料 前端控制器
 * </p>
 *
 * @author zhangbanglong
 * @since 2020-08-28
 */
@RestController
@RequestMapping("/radiationMin")
@Api(tags = "辐射资料-中国气象辐射逐分钟资料  --接口")
public class RadiationMinController {
	
	private static final Logger logger = LoggerFactory.getLogger(GroundPreController.class);
	@Autowired
	private RadiationMinService radiationMinService;
	
	@Autowired
	private RadiationMinMapper radiationMinMapper;
	
	@Autowired
	private RadiationMinExcelDtoService radiationMinExcelDtoService;
	
	@Value("${excelfilePortPrefix}")
	private String excelfilePortPrefix;

	@Value("${excelfileUri}")
	private String excelfileUri;
	
	/**
	 * 按条件查询地面数据接口 <br/>
	 * json格式 传递参数
	 * 
	 * @param WeatherDataQueryDto
	 *            查询参数
	 * @throws Exception
	 * 
	 */
	@ApiOperation(value = "按条件分页查询 辐射资料-中国气象辐射逐分钟资料    接口", notes = "分页查询  辐射资料-中国气象辐射逐分钟资料")
	@RequestMapping(value = "/getRadiationMinByDto", method = RequestMethod.POST)
	public Object getListByDto(@RequestBody WeatherDataQueryDto weatherDataQueryDto) throws Exception {

		PageDto<RadiationMinListDto> pageDto = new PageDto<RadiationMinListDto>();
		pageDto.setSize(weatherDataQueryDto.getSize());
		pageDto.setCurrent(weatherDataQueryDto.getCurrent());

		IPage<RadiationMinListDto> userIPage = radiationMinService.getList(pageDto, weatherDataQueryDto);
		// IPage<GroundDataListDto> data= groundDataService.getList(page,
		// weatherDataQueryDto);
		ResultEntity result = new ResultEntity(ResultCodeEnum.SUCCESS, userIPage, true);
		Map<String, Object> map = ResultUtil.resultMap(result);
		return map;
	};

	/**
	 * 根据id查询地面数据 <br/>
	 * 
	 * @param WeatherDataQueryDto
	 *            查询参数
	 * 
	 */
	@ApiOperation(value = "根据id查询辐射资料-中国气象辐射逐分钟资料", notes = "查询 辐射资料-中国气象辐射逐分钟资料  ,返回  全部值")
	@ApiImplicitParam(name = "id", value = "地面数据id", dataType = "string", paramType = "query", example = "1288343101566914578")
	@RequestMapping(value = "/getRadiationMinById", method = RequestMethod.POST)
	public Object getGroundDataById(@RequestParam(value = "id", required = true) String id) {
		
		RadiationMin gd = radiationMinMapper.selectById(id);
		ResultEntity result = null;
		if (gd != null) {
			result = new ResultEntity(ResultCodeEnum.SUCCESS, gd, true);
		} else {
			result = new ResultEntity(ResultCodeEnum.FAILURE, null, false);
		}

		Map<String, Object> map = ResultUtil.resultMap(result);
		return map;
	};
	
	
	/**
	 * 
	 * 可能抛出的异常 IOException
	 * 
	 * @throws Exception
	 * 
	 */
	@ApiOperation(value = "动态导出excel", notes = "根据前台传入的 查询列，与字段含义,动态查询数据并导出，请确保列数 =字段含义数   <br> 例子：{\"dateEnd\":\"2020-03-03 00:00:00\",\"dateStart\":\"2020-03-01 00:00:00\",\"selectFilds\":\"ground_data_id,data_query_id,create_time,data_time\",\"selectUnits\":\"数据id,查询id,创建时间,数据时间\"}", produces = "application/json")
	@RequestMapping(value = "/export", method = RequestMethod.POST)
	public Object exporGroundTem(@RequestBody ExportDto exportDto) throws Exception {

		String filename = exportDto.getDateStart().replace(":", "") + "-" + exportDto.getDateEnd().replace(":", "");
				
		filename = filename.replace(" ", "");
		
		
		String path = excelfilePortPrefix + File.separator + this.excelfileUri + File.separator + filename;
		

		if ("true".equals(exportDto.getExportAllFlag())) {
			List<RadiationMinExcelDto> list =radiationMinExcelDtoService.getList(exportDto);
			// String filename="地面数据导出";
			String suffix="辐射资料-中国气象辐射逐分钟资料-全部字段导出.xlsx";
			File file = new File(path+suffix);
			boolean flag=WeatherDataUtil.writeExcel(list, file, "辐射资料-中国气象辐射逐分钟资料", RadiationMinExcelDto.class);
			
			ResultEntity result = null;
			ExportResponseDto dto = new ExportResponseDto();
			
			if (flag) {
				//返回  访问静态文件的 后缀地址  前缀地址 前端来处理
				String excelUrl = this.excelfileUri + "/" + filename+suffix;
				dto.setFilepath(excelUrl);
				result = new ResultEntity(ResultCodeEnum.SUCCESS, dto, true);
			} else {
				result = new ResultEntity(ResultCodeEnum.FAILURE, null, false);
			}
			return result;
		}
		
		

		// 导出文件的名字
		// String filename="地面数据导出";
		// 工作簿名称
		String sheetName = "辐射资料-中国气象辐射逐分钟资料";
		// 所有行数据，每一行其实就是一个封装的实体对象
		List<Map<String, Object>> listMap = radiationMinService.getListMap(exportDto);

		String untis = exportDto.getSelectUnits();
		// 标题集合
		List<String> untisList = WeatherDataUtil.strToArrayList(untis);
		Iterator<String> iteru = untisList.iterator();

		String fileds = exportDto.getSelectFilds();
		// 查询字段集合
		List<String> filedsList = WeatherDataUtil.strToArrayList(fileds);
		// Iterator<String> iterf=filedsList.iterator();

		List<ArrayList<Object>> listdata = new ArrayList<ArrayList<Object>>();

		Iterator<Map<String, Object>> iter = listMap.iterator();

		// 循环处理 值
		while (iter.hasNext()) {
			Map<String, Object> mp = iter.next();
			Iterator<String> iterf = filedsList.iterator();
			ArrayList<Object> data = new ArrayList<Object>();
			while (iterf.hasNext()) {
				String str = iterf.next();
				data.add(mp.get(str));
			}
			listdata.add(data);
		}

		// 循环创建 标题
		List<List<String>> headList = new ArrayList<>();
		while (iteru.hasNext()) {
			String str = iteru.next();
			List<String> head = new ArrayList<>();
			head.add(str);
			headList.add(head);
		}
		ResultEntity result = null;

		try {
			String suffix="辐射资料-中国气象辐射逐分钟资料-部分字段导出.xlsx";
			File file = new File(path+suffix);
			boolean flag = WeatherDataUtil.writeDynamicHeadExcel(listdata, file, sheetName, GroundDataExcelDto.class,headList);
			ExportResponseDto dto = new ExportResponseDto();
			
			if (flag) {
				//返回  访问静态文件的 后缀地址  前缀地址 前端来处理
				String excelUrl = this.excelfileUri + "/" + filename+suffix;
				dto.setFilepath(excelUrl);
				result = new ResultEntity(ResultCodeEnum.SUCCESS, dto, true);
			} else {
				result = new ResultEntity(ResultCodeEnum.FAILURE, null, false);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 
	 * 可能抛出的异常 IOException
	 * 
	 * @throws Exception
	 * 
	 */
	@ApiOperation(value = "查询动态导出excel的行数", notes = "请传入 查询条件  例子：{\"dateEnd\":\"2020-03-03 00:00:00\",\"dateStart\":\"2020-03-01 00:00:00\",\"selectFilds\":\"ground_data_id,data_query_id,create_time,data_time\",\"selectUnits\":\"数据id,查询id,创建时间,数据时间\"}", produces = "application/json")
	@RequestMapping(value = "/exportCount", method = RequestMethod.POST)
	public Object exportGroundTemCount(@RequestBody ExportDto exportDto) throws Exception {

		int count = radiationMinService.getListMapCount(exportDto);

		ResultEntity result = null;
		if (count >= 0) {
			ExportResponseDto ed = new ExportResponseDto();
			ed.setCount(count);
			result = new ResultEntity(ResultCodeEnum.SUCCESS, ed, true);
		} else {
			result = new ResultEntity(ResultCodeEnum.FAILURE, null, false);
		}

		Map<String, Object> map = ResultUtil.resultMap(result);
		return map;

	}

}
